package com.apache.common.plugins.flow;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.client.UctProtoclClient;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.tools.UUIDUtil;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提交审核时，初始化审核表audit。
 */
@SuppressWarnings("serial")
public class FlowInitPluginImpl implements CustomMethodPlugin {

    protected Logger log = LoggerFactory.getLogger(getClass());

    public Object doInvoke(Map<String, Object> param) {

        //1. ifStart=T and auditType=参数
        //list

        //2.通过遍历每个节点获取其nodeConfig，进行解析找到next节点编号

        //3.根据next节点编号获取当前节点，判断当前节点的nodeType是否为task节点，如果是task节点，存到审核表中，如果是judge节点，重复第二步



        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 初始化审核表
     * params：
     */
    public Object beforeInvoke(Map<String, Object> param) {
        String auditType = String.valueOf(param.get("auditType"));//流程类型
        String auditsId = String.valueOf(param.get("auditsId"));
        String proId = String.valueOf(param.get("pid"));//业务主键id
        String proNo = String.valueOf(param.get("proNo"));//业务编号
        String proName = String.valueOf(param.get("proName"));//业务名称
        String taskType = String.valueOf(param.get("taskType"));
        String linkName = String.valueOf(param.get("linkName"));//伤者名称
        String linkManTel = String.valueOf(param.get("linkManTel"));//伤者电话
        String personId = String.valueOf(param.get("personId"));//伤者id
        String lastId = String.valueOf(param.get("lastId"));//上一环节业务主键
        String dispatchStatus = String.valueOf(param.get("dispatchStatus"));//调度环节
        String isRevision = String.valueOf(param.get("isRevision"));//标记是否改派
        String taskSource = String.valueOf(param.get("taskSource"));//来源
        String delStatus = String.valueOf(param.get("delStatus"));//唯一索引标识
        String deptId = String.valueOf(param.get("deptId"));//唯一索引标识
        String district = String.valueOf(param.get("district"));//任务区县代码
        //非必须
        String userEname = String.valueOf(param.get("userEname"));
        String userCname = String.valueOf(param.get("userCname"));
        String orgId = String.valueOf(param.get("orgId"));



        ResultEntity reslutEntity = new ResultEntity();
        if (Validator.isNull(proId)) {
            proId = UUIDUtil.generateId();
        }
        if (Validator.isNull(auditType)) {
            throw new BusinessException("提交审核时auditType参数不能为空！");
        }
        log.info("【启动审核任务】 - > auditType="+auditType+",proId="+proId);
        String ifStart = "T";

        //找到开始节点（有可能出现多个）
        String searchObjName = "s_sysAuditRule";
        Map<String, Object> whereMap = new HashMap<String, Object>();
        whereMap.put("sysAuditRule.w_auditType", auditType);
        whereMap.put("sysAuditRule.w_ifStart", ifStart);
        whereMap.put("sysAuditRule.w_nodeType", "start");
        ResultEntity dymicSqlParamResult = (ResultEntity) IusPluginUtil.getInstance().select(String.valueOf(param.get("datasource")),"list",searchObjName,whereMap);
        List<DataMap> firstNodeList = (List<DataMap>) dymicSqlParamResult.getEntity();
        String nextNodeCode="";


        String objName ="";
        String colName = "";

        for (DataMap node:firstNodeList) {
            String nodeType="";
            nodeType = String.valueOf(node.get("nodeType"));
            String nodeConfig = String.valueOf(node.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray)jObject.get("nexts");
            if(jsonArray.size()>0){
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nextNodeCode = String.valueOf(job.get("code"));
                    DataMap nextTaskNodeInfo = getNodeByCode(param,nextNodeCode);

                    if(nextTaskNodeInfo!=null){
//                        System.out.println("======================="+nextTaskNodeInfo.get("taskName"));
                        if(!"end".equals(nextTaskNodeInfo.get("nodeType"))){
                            nextTaskNodeInfo.put("pid",proId);
                            nextTaskNodeInfo.put("pro_id",proNo);
                            nextTaskNodeInfo.put("pro_name",proName);//车牌号
                            nextTaskNodeInfo.put("col_name_y",taskType);
                            nextTaskNodeInfo.put("col_name_n",linkName);//伤者名称
                            nextTaskNodeInfo.put("link_url",linkManTel);//伤者电话
                            nextTaskNodeInfo.put("person_id",personId);//伤者ID
                            nextTaskNodeInfo.put("last_id",lastId);//上一环节业务主键
                            nextTaskNodeInfo.put("dispatch_status",dispatchStatus);//上一环节业务主键
                            nextTaskNodeInfo.put("audits_id",auditsId);//预生产主键
                            nextTaskNodeInfo.put("del_status",delStatus);//唯一索引
                            nextTaskNodeInfo.put("dept_id",deptId);//
                            if(Validator.isNotNull(district)) {
                                nextTaskNodeInfo.put("district", district);//任务区县代码
                            }
                            if(Validator.isNotNull(isRevision)) {
                                nextTaskNodeInfo.put("is_revision", isRevision);//是否改派标记
                            }
                            if(Validator.isNotNull(taskSource)) {
                                nextTaskNodeInfo.put("task_source", taskSource);//来源
                            }
                            if(Validator.isNotNull(userEname)&&(!"6".equals(taskType)&&!"7".equals(taskType))){
                                nextTaskNodeInfo.put("check_user",userEname);
                            }else{
                                String checkType = String.valueOf(nextTaskNodeInfo.get("checkType"));
                                if("rule".equals(checkType)){
                                    String checkUser = String.valueOf(nextTaskNodeInfo.get("checkUser"));
                                    Map<String, Object> paramsMap = new HashMap<String, Object>();
                                    paramsMap.put("roleId",checkUser);
                                    paramsMap.put("doCode","userList");
                                    paramsMap.put("Client-IP",param.get("requestIp"));
                                    paramsMap.put("sysPass",param.get("sysPass"));
                                    InterfaceRegister ss =  UctProtoclClient.getInstance().getInterfaceRegister("uct", "uctServer_ip", "uctServer_port");
                                    ResultEntity entity =  LoadRpcService.service().doServiceClient("uctService", "userList", paramsMap,ss);
                                    String checkUsers = "";
                                    if(null != entity.getEntity()){
                                        List<User> userList =(List<User>)entity.getEntity();
                                        for (User user: userList) {
                                            checkUsers = checkUsers==""?user.getUserEname():checkUsers+","+user.getUserEname();
                                        }
                                        nextTaskNodeInfo.put("check_user",checkUsers);
                                    }
                                }
                            }
                            if(Validator.isNotNull(userCname)){
                                nextTaskNodeInfo.put("user_name",userCname);
                            }
                            if(Validator.isNotNull(orgId)){
                                nextTaskNodeInfo.put("org_id",orgId);
                            }
                            nextTaskNodeInfo.put("datasource",String.valueOf(param.get("datasource")));
                            //ifCustom:
                                // 为空或者1:checkUser=userEname1,userEname2 的格式
                                //2:checkUser=角色
                                //3、抢占模式，会产生多条checkUser，每个checkUser=userEname
                                //4、半数通过模式，会产生多条checkUser，每个checkUser=userEname
                                //5、全票通过模式，会产生多条checkUser，每个checkUser=userEname


                            reslutEntity = initAudit(nextTaskNodeInfo);
//                            objName = String.valueOf(nextTaskNodeInfo.get("tableName"));
//                            colName = String.valueOf(nextTaskNodeInfo.get("colName"));

                        }else{
                            log.info("【已到结束节点】流程结束！！");
                        }
                    }

                }
            }

        }


//        if (Validator.isNotNull(objName) && Validator.isNotNull(colName)) {
//            param.put(objName + "." + colName, proId);
//            return param;
//        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put(CustomMethodPlugin.resultMark, "操作成功");
        result.put(CustomMethodPlugin.pluginInnerReturn, reslutEntity.getEntity());
        return result;

    }

    public Object afterInvoke(Map<String, Object> param) {

        return null;
    }


    private ResultEntity initAudit(DataMap taskMap){
            String saveObjName = "i_sysAudit";
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("sysAudit.auditsId",taskMap.get("auditsId"));
            paramsMap.put("sysAudit.auditType",taskMap.get("auditType"));
            paramsMap.put("sysAudit.proId",taskMap.get("proId"));
            paramsMap.put("sysAudit.pid",taskMap.get("pid"));
            paramsMap.put("sysAudit.auditsStatus", "10");
            paramsMap.put("sysAudit.checkUser", taskMap.get("checkUser"));
            paramsMap.put("sysAudit.userName", taskMap.get("userName"));
            paramsMap.put("sysAudit.nextUser", taskMap.get("next"));
            paramsMap.put("sysAudit.lastUser", taskMap.get("last"));
            paramsMap.put("sysAudit.toUrl", taskMap.get("toUrl"));
            paramsMap.put("sysAudit.createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
            paramsMap.put("sysAudit.num", taskMap.get("num"));
            paramsMap.put("sysAudit.colNameY", taskMap.get("colNameY"));
            paramsMap.put("sysAudit.colNameN", taskMap.get("colNameN"));
            paramsMap.put("sysAudit.linkUrl", taskMap.get("linkUrl"));
            paramsMap.put("sysAudit.personId", taskMap.get("personId"));
            paramsMap.put("sysAudit.lastId", taskMap.get("lastId"));
            paramsMap.put("sysAudit.dispatchStatus", taskMap.get("dispatchStatus"));
            paramsMap.put("sysAudit.isRevision", taskMap.get("isRevision"));
            paramsMap.put("sysAudit.taskSource", taskMap.get("taskSource"));
            paramsMap.put("sysAudit.ifCustom", taskMap.get("ifCustom"));
            paramsMap.put("sysAudit.sysName", taskMap.get("sysName"));
            paramsMap.put("sysAudit.pageName", taskMap.get("pageName"));
            paramsMap.put("sysAudit.formName", taskMap.get("formName"));


            paramsMap.put("sysAudit.proName", taskMap.get("proName"));
            paramsMap.put("sysAudit.orgId", taskMap.get("orgId"));
            paramsMap.put("sysAudit.taskName", taskMap.get("taskName"));
            paramsMap.put("sysAudit.taskNo", taskMap.get("taskNo"));
            paramsMap.put("sysAudit.colName", taskMap.get("colName"));
            paramsMap.put("sysAudit.tableName", taskMap.get("tableName"));
            paramsMap.put("sysAudit.delStatus", taskMap.get("delStatus"));
            paramsMap.put("sysAudit.deptId", taskMap.get("deptId"));
            paramsMap.put("sysAudit.district", taskMap.get("district"));//区县代码
            ResultEntity result = IusPluginUtil.getInstance().saveInvoke(String.valueOf(taskMap.get("datasource")),saveObjName,paramsMap);
//            log.info("【初始化第一级审核任务结果】 - > taskName="+taskName+",proName="+name+",result="+ JSONObject.fromObject(result));

            if (!result.getResult().equals("T")) {
                throw new BusinessException("执行失败！");
            }
            return result;

    }

    private DataMap getNodeByCode(Map<String, Object> param,String nodeCode) {
        if(StrUtil.isNull(nodeCode)){
            return  null;
        }
        Map<String, Object> whereMap_next = new HashMap<String, Object>();
        whereMap_next.put("sysAuditRule.w_taskNo", nodeCode);
        ResultEntity nextCodeResult = (ResultEntity) IusPluginUtil.getInstance().select(String.valueOf(param.get("datasource")), "obj", "s_sysAuditRule", whereMap_next);
        DataMap nextNodeInfo = (DataMap) nextCodeResult.getEntity();
        String next_nodeType = String.valueOf(nextNodeInfo.get("nodeType"));
        if ("judge".equals(next_nodeType)) {
            //递归
            String nextNode = "";
            String nodeConfig = String.valueOf(nextNodeInfo.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray) jObject.get("nexts");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nodeCode = String.valueOf(job.get("code"));
                    String rule = String.valueOf(job.get("rule"));
                    if(Validator.isNotNull(rule)){
                        String arg1 = rule.split("==")[0];
                        String arg2 = rule.split("==")[1];
                        if (arg2.equals(param.get(arg1))) {
                            nextNode = String.valueOf(job.get("code"));
                            break;
                        }
                    }
                }
            }
            return getNodeByCode(param, nextNode);
        }
    return nextNodeInfo;
    }
    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
//        beforeInvoke(paramsVo.getParams());
    }

}
